/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package site.shihuan.helpdesk.security.manager;

import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import site.shihuan.helpdesk.common.config.AuthConfigs;
import site.shihuan.helpdesk.common.manager.TokenManager;
import site.shihuan.helpdesk.common.model.Constants;
import site.shihuan.helpdesk.common.model.JwtUser;
import site.shihuan.helpdesk.common.model.Permission;
import site.shihuan.helpdesk.security.exception.AccessException;

import javax.servlet.http.HttpServletRequest;


/**
 * 鉴权
 *
 * @author 周世焕
 * @Date 2021/1/23 11:49
 */
@Component
@Slf4j
public class AuthManager{

    private static final String TOKEN_PREFIX = "Bearer ";

    @Autowired
    private TokenManager tokenManager;

    /**
     * 身份验证
     * @param request
     * @return
     * @throws AccessException
     */
    public JwtUser authenticate(Object request) throws AccessException {
        HttpServletRequest req = (HttpServletRequest) request;

        String token = resolveToken(req);

        try {
            tokenManager.validateToken(token);
        } catch (ExpiredJwtException e) {
            throw new AccessException("token expired!");
        } catch (Exception e) {
            throw new AccessException("token invalid!");
        }

        JwtUser user = tokenManager.getUserInfo(token);
        return user;
    }

    /**
     * 权限验证
     * @param permission
     * @param user
     * @throws AccessException
     */
    public void authorize(Permission permission, JwtUser user) throws AccessException {
        //TODO 应该从Redis中读取user role对应的resources列表，比对资源是否在列表中
    }

    /**
     * 从请求头或者请求参数中获取token
     */
    private String resolveToken(HttpServletRequest request) throws AccessException {
        String bearerToken = request.getHeader(AuthConfigs.AUTHORIZATION_HEADER);
        if (StringUtils.isNotBlank(bearerToken) && bearerToken.startsWith(TOKEN_PREFIX)) {
            return bearerToken.substring(7);
        }
        bearerToken = request.getParameter(Constants.ACCESS_TOKEN);
        if (StringUtils.isBlank(bearerToken)) {
            throw new AccessException("token not exists!");
        }
        return bearerToken;
    }
}
